#pragma once

#define _GNU_SOURCE
#include <strings.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <stddef.h>
#include <ctype.h>
#include <assert.h>
#include <errno.h>
#include <math.h>

#define MY_INT32_LEN                                (sizeof("-2147483648") - 1)
#define MY_INT64_LEN                                (sizeof("-9223372036854775808") - 1)

typedef uint8_t                                     my_bool_t;
#define MY_FALSE                                    0
#define MY_TRUE                                     1

/* 0-99 is normal result code in my_result_t variable */
typedef uint32_t                                    my_result_t;
#define MY_FAILED                                   0
#define MY_SUCCESS                                  1
#define MY_AGAIN                                    2
#define MY_TIMEOUT                                  3
#define MY_BUSY                                     4
#define MY_EOS                                      5
/* 100-999 is http status code in my_result_t variable */
#define MY_HTTP_CODE_BEGIN                          100
/* 1000-1999 is custom http error code */
#define MY_HTTP_ERR_CODE_BEGIN                      1000
/* 2000-2999 is linux error code */
#define MY_SYSTEM_ERR_CODE_BEGIN                    2000

#define INVALID_FD                                  -1

#define LF                                          '\n'
#define CR                                          '\r'
#define CRLF                                        "\r\n"
#define CRLF_LEN                                    2

#define MY_ABS(value)                               (((value) >= 0) ? (value) : - (value))
#define MY_SWAP(a, b, tmp)                          {tmp=a; a=b; b=tmp;}
#define MY_MAX(val1, val2)                          ((val1 < val2) ? (val2) : (val1))
#define MY_MIN(val1, val2)                          ((val1 > val2) ? (val2) : (val1))

#define MY_ALIGN(d, a)                              (((d) + (a - 1)) & ~(a - 1))
#define MY_ALIGN_PTR(p, a)                          \
    (u_char *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1))

#define MY_PAGE_BITS                                12
#define MY_PAGE_SIZE                                (1 << MY_PAGE_BITS) // 1 << 12 = 4K
#define MY_PAGE_MASK                                (MY_PAGE_SIZE - 1)  // 4K - 1

#define MY_ALIGN_PAGE_SIZE(size)            \
    ((size + MY_PAGE_MASK) & (~MY_PAGE_MASK))

#define MY_IS_PAGE_ALIGNED(size)            \
    ((size&MY_PAGE_MASK) == 0)


#define MY_SCHED_YIELD              usleep(1)


#define MY_CASTBIT(val, width)      ((val) & ((1ULL << width) - 1))